/**
 * @author Paulo Faria Reis
 * @created 22 Mar 2012
 *
 */
package networkoperations;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.MulticastSocket;
import java.util.Random;

import controller.DataStore;

/**
 * @author Paulo Faria Reis
 * Receives a string with the text to find, multicast channel address and port.
 */
public class Searcher {
   DataStore dataStorage;
   MulticastSocket controlSocket;

   /**
    * @author Paulo Faria Reis
    * @throws IOException 
    */
   public Searcher(DataStore dataStor){
	dataStorage = dataStor; 
   }

   /**
    * Creates and sends a FOUND datagram.
    * @param whatToFind
    */
   public void lookFor(String whatToFind){
	// create a random int for id	
	try {
	   Random randomChunk = new Random();
	   int randomInt = randomChunk.nextInt(899999999);
	   randomInt += 100000000;	// randomInt will be between 100000000 and 999999999, that is 9 digits wide.
	   byte[] msgOut = ("SEARCH id" + randomInt + " " + whatToFind).getBytes();	// Message of packet for the search.
	   dataStorage.resetSearch("SEARCH id" + randomInt);	// Prepares a new search.
	   DatagramPacket announcer = new DatagramPacket(msgOut, msgOut.length, dataStorage.getMcAddress(), dataStorage.getControlPort());
	   controlSocket = new MulticastSocket(dataStorage.getControlPort());
	   controlSocket.joinGroup(dataStorage.getMcAddress());
	   controlSocket.setTimeToLive(1);
	   controlSocket.send(announcer);
	   controlSocket.leaveGroup(dataStorage.getMcAddress());
	   controlSocket.close();
	}
	catch (IOException e) {
	   System.out.println("Failure to send the FOUND datagram.");
	}
   }
}
